package com.xone.collaboration.service.impl.strategy;

import com.xone.collaboration.service.OpStrategy;
import com.xone.collaboration.service.aonntation.Strategy;
import com.xone.collaboration.service.impl.process.OperationContext;
import com.xone.collaboration.service.vo.OperationResult;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@Component
public class OpStrategyInvoker implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public OperationResult invoke(OperationContext context){
        Map<String, Object> strategy =  applicationContext.getBeansWithAnnotation(Strategy.class);
         AtomicReference<OpStrategy> invoker  = new AtomicReference<>();
          strategy.keySet().forEach(key->{
            OpStrategy opStrategy = (OpStrategy)strategy.get(key);
            Strategy annotation = opStrategy.getClass().getAnnotation(Strategy.class);
            if(annotation.value().equals(context.getOpType().getValue())){
                invoker.set(opStrategy);
            }
        });
       return invoker.get().operate(context);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
